package ltd.nullpointer.frontend.schedule;

import com.alibaba.fastjson.JSONObject;
import com.boot2.core.HlAssert;
import com.boot2.core.dao.i.SchedulerTaskDao;
import com.boot2.core.po.SchedulerTask;
import com.boot2.core.scheduler.ScheduleManager;
import com.boot2.core.scheduler.SchedulerJobDataMapConsant;
import com.boot2.core.utils.CronExpressionUtil;
import lombok.extern.apachecommons.CommonsLog;
import ltd.nullpointer.frontend.dao.SchedulerTaskToSendTCPMessageDao;
import ltd.nullpointer.frontend.model.entity.SchedulerTaskToSendTCPMessage;
import ltd.nullpointer.tcp.core.TCPMessageProducer;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * @author zhangweilin
 * @Description: xxxxx
 * @date 2019/12/19
 */
@Service
@CommonsLog
public class SchedulerTaskSensorDataService {

    @Autowired
    SchedulerTaskToSendTCPMessageDao schedulerTaskToSendTCPMessageDao;

    @Autowired
    SchedulerTaskDao schedulerTaskDao;

    @Autowired
    ScheduleManager scheduleManager;

    @Autowired
    TCPMessageProducer tcpMessageProducer;

    /**
     * 下发tcp消息, 对应code:  SchedulerTaskConstant.send_tcp_message
     *
     * @param jobExecutionContext
     */
    public void sendTCPMessage(JobExecutionContext jobExecutionContext) {
        Long id = jobExecutionContext.getMergedJobDataMap().getLong(SchedulerJobDataMapConsant.bussinessId);
        Assert.notNull(id, "调度任务，没有id");
        SchedulerTaskToSendTCPMessage schedulerTaskToSendTCPMessage = schedulerTaskToSendTCPMessageDao.findOne(id);
        Assert.notNull(schedulerTaskToSendTCPMessage, "找不到此schedulerTaskMqttMessage,id: " + id);
        String paramJson = schedulerTaskToSendTCPMessage.getParamJson();
        String deviceSn = schedulerTaskToSendTCPMessage.getSensorNo();

        //beanClassName:ltd.nullpointer.frontend.model.entity.down.GetSensorData,
        JSONObject jsonObject = JSONObject.parseObject(paramJson);
        String beanClassName = jsonObject.getString(SchedulerTaskConstant.beanClassName);
        String beanJsonValue = jsonObject.getString(SchedulerTaskConstant.beanJsonValue);
        Object object = null;
        try {
            object = JSONObject.parseObject(beanJsonValue, Class.forName(beanClassName));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            log.error("定时下发tcp消息失败",e);
        }
        try {
            tcpMessageProducer.sendToDevice(deviceSn, object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Boolean isDeleteOneTime = schedulerTaskToSendTCPMessage.getIsDeleteOneTime();
        isDeleteOneTime = isDeleteOneTime != null;
      //  mqttProducer.send(MqttConstatnt.down_server_prefix + deviceSn, mqttMessage);
        Date nextFireTime = jobExecutionContext.getNextFireTime();
        if (null==nextFireTime&&isDeleteOneTime) {
            schedulerTaskToSendTCPMessageDao.delete(schedulerTaskToSendTCPMessage);
        }else{
            schedulerTaskToSendTCPMessage.setNextFireTime(nextFireTime);
            schedulerTaskToSendTCPMessageDao.saveAndFlush(schedulerTaskToSendTCPMessage);
        }
    }


    /**
     * 添加和调用一个新任务
     *
     * @param deviceSn
     * @param paramJson
     * @param remark
     * @param cronExpression
     */
    public void addAndSchedule(String deviceSn, String paramJson, String remark, String cronExpression, Boolean isDeleteOneTime) {
        boolean canDoExpression = CronExpressionUtil.isCanDoExpression(cronExpression);
        HlAssert.isTrue(canDoExpression, "一次性调度任务，时间不能在当前时间之前");

        SchedulerTaskToSendTCPMessage schedulerTaskToSendTCPMessage = new SchedulerTaskToSendTCPMessage(true);
        schedulerTaskToSendTCPMessage.setParamJson(paramJson);
//        schedulerTaskToSendTCPMessage.setStatus(0);
        schedulerTaskToSendTCPMessage.setCronExpression(cronExpression);
        schedulerTaskToSendTCPMessage.setSensorNo(deviceSn);
        schedulerTaskToSendTCPMessage.setRemark(remark);
        schedulerTaskToSendTCPMessage.setIsDeleteOneTime(isDeleteOneTime);
        schedulerTaskToSendTCPMessage.setCreateTime();
        schedulerTaskToSendTCPMessageDao.saveAndFlush(schedulerTaskToSendTCPMessage);
        SchedulerTask schedulerTask = new SchedulerTask(true);
        schedulerTask.setCronExpression(cronExpression);
        schedulerTask.setBussinessId(schedulerTaskToSendTCPMessage.getId());
        schedulerTask.setCode(SchedulerTaskConstant.send_tcp_message);
        schedulerTask.setRetryTimes(0);
        schedulerTask.setIsEnabled(true);
        schedulerTask.setIsConcurrent(true);
        schedulerTask.setName("定时下发TCP消息");
        schedulerTask.setRemark(remark);
        schedulerTask.setCreateTime();
        schedulerTaskDao.saveAndFlush(schedulerTask);
        scheduleManager.scheduleOrResumeATask(schedulerTask.getId());
    }

    /**
     * 删除一个定时任务
     *
     * @param schedulerTaskMqttMessage
     */
    public void delete(SchedulerTaskToSendTCPMessage schedulerTaskToSendTCPMessage) {
        schedulerTaskToSendTCPMessageDao.delete(schedulerTaskToSendTCPMessage);
        SchedulerTask schedulerTask = schedulerTaskDao.findByCodeAndBussinessId(SchedulerTaskConstant.send_tcp_message, schedulerTaskToSendTCPMessage.getId());
        if (null != schedulerTask) {
            scheduleManager.stopTask(schedulerTask.getId());
        }
    }
}
